#!/bin/bash

# 商家后端系统部署脚本
# 使用方法: ./deploy.sh [环境] [操作]
# 环境: dev|test|prod
# 操作: start|stop|restart|status

set -e

# 配置变量
APP_NAME="merchant-backend"
APP_VERSION="1.0.0"
JAR_NAME="spring-boot2-0.0.1-SNAPSHOT.jar"
APP_HOME="/opt/merchant-backend"
LOG_DIR="/var/log/merchant-backend"
PID_FILE="$APP_HOME/app.pid"

# 环境配置
ENVIRONMENT=${1:-dev}
ACTION=${2:-start}

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Java环境
check_java() {
    if ! command -v java &> /dev/null; then
        log_error "Java is not installed or not in PATH"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
    log_info "Java version: $JAVA_VERSION"
}

# 检查MySQL连接
check_mysql() {
    log_info "Checking MySQL connection..."
    if ! command -v mysql &> /dev/null; then
        log_warn "MySQL client not found, skipping connection check"
        return
    fi
    
    # 这里可以添加MySQL连接检查逻辑
    log_info "MySQL connection check passed"
}

# 创建必要的目录
create_directories() {
    log_info "Creating necessary directories..."
    sudo mkdir -p $APP_HOME
    sudo mkdir -p $LOG_DIR
    sudo mkdir -p /var/uploads
    
    # 设置权限
    sudo chown -R $USER:$USER $APP_HOME
    sudo chown -R $USER:$USER $LOG_DIR
    sudo chown -R $USER:$USER /var/uploads
}

# 构建应用
build_app() {
    log_info "Building application..."
    mvn clean package -DskipTests
    
    if [ ! -f "target/$JAR_NAME" ]; then
        log_error "Build failed: JAR file not found"
        exit 1
    fi
    
    log_info "Build completed successfully"
}

# 部署应用
deploy_app() {
    log_info "Deploying application..."
    
    # 备份旧版本
    if [ -f "$APP_HOME/$JAR_NAME" ]; then
        cp "$APP_HOME/$JAR_NAME" "$APP_HOME/${JAR_NAME}.backup.$(date +%Y%m%d_%H%M%S)"
        log_info "Old version backed up"
    fi
    
    # 复制新版本
    cp "target/$JAR_NAME" "$APP_HOME/"
    log_info "New version deployed"
}

# 启动应用
start_app() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            log_warn "Application is already running (PID: $PID)"
            return
        else
            rm -f $PID_FILE
        fi
    fi
    
    log_info "Starting application in $ENVIRONMENT environment..."
    
    # 设置JVM参数
    JVM_OPTS="-Xms512m -Xmx1024m"
    JVM_OPTS="$JVM_OPTS -XX:+UseG1GC"
    JVM_OPTS="$JVM_OPTS -XX:MaxGCPauseMillis=200"
    JVM_OPTS="$JVM_OPTS -XX:+UseStringDeduplication"
    JVM_OPTS="$JVM_OPTS -Djava.security.egd=file:/dev/./urandom"
    
    # 设置应用参数
    APP_OPTS="--spring.profiles.active=$ENVIRONMENT"
    APP_OPTS="$APP_OPTS --server.port=8080"
    
    # 启动应用
    nohup java $JVM_OPTS -jar "$APP_HOME/$JAR_NAME" $APP_OPTS \
        > "$LOG_DIR/application.out" 2>&1 &
    
    echo $! > $PID_FILE
    
    # 等待启动
    sleep 5
    
    if ps -p $(cat $PID_FILE) > /dev/null 2>&1; then
        log_info "Application started successfully (PID: $(cat $PID_FILE))"
    else
        log_error "Application failed to start"
        exit 1
    fi
}

# 停止应用
stop_app() {
    if [ ! -f "$PID_FILE" ]; then
        log_warn "PID file not found, application may not be running"
        return
    fi
    
    PID=$(cat $PID_FILE)
    
    if ! ps -p $PID > /dev/null 2>&1; then
        log_warn "Application is not running (PID: $PID)"
        rm -f $PID_FILE
        return
    fi
    
    log_info "Stopping application (PID: $PID)..."
    
    # 优雅停止
    kill -TERM $PID
    
    # 等待停止
    for i in {1..30}; do
        if ! ps -p $PID > /dev/null 2>&1; then
            log_info "Application stopped successfully"
            rm -f $PID_FILE
            return
        fi
        sleep 1
    done
    
    # 强制停止
    log_warn "Force stopping application..."
    kill -KILL $PID
    rm -f $PID_FILE
    log_info "Application force stopped"
}

# 检查应用状态
check_status() {
    if [ ! -f "$PID_FILE" ]; then
        log_info "Application is not running"
        return 1
    fi
    
    PID=$(cat $PID_FILE)
    
    if ps -p $PID > /dev/null 2>&1; then
        log_info "Application is running (PID: $PID)"
        
        # 检查健康状态
        if command -v curl &> /dev/null; then
            if curl -f -s http://localhost:8080/test/health > /dev/null; then
                log_info "Application health check passed"
            else
                log_warn "Application health check failed"
            fi
        fi
        return 0
    else
        log_warn "PID file exists but application is not running"
        rm -f $PID_FILE
        return 1
    fi
}

# 重启应用
restart_app() {
    log_info "Restarting application..."
    stop_app
    sleep 2
    start_app
}

# 主函数
main() {
    log_info "Merchant Backend Deployment Script"
    log_info "Environment: $ENVIRONMENT"
    log_info "Action: $ACTION"
    
    # 检查环境
    check_java
    
    case $ACTION in
        "build")
            build_app
            ;;
        "deploy")
            create_directories
            build_app
            deploy_app
            ;;
        "start")
            create_directories
            start_app
            ;;
        "stop")
            stop_app
            ;;
        "restart")
            restart_app
            ;;
        "status")
            check_status
            ;;
        "full-deploy")
            create_directories
            check_mysql
            build_app
            deploy_app
            restart_app
            check_status
            ;;
        *)
            echo "Usage: $0 [environment] [action]"
            echo "Environment: dev|test|prod"
            echo "Actions: build|deploy|start|stop|restart|status|full-deploy"
            exit 1
            ;;
    esac
    
    log_info "Operation completed"
}

# 执行主函数
main
